package cn.genmer.test.security.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

public class ExportExcelUtil {
    public static <T> void exportExcel(List dataList , Class<T> entityModel , HttpServletResponse response) {
        if (StringUtils.isEmpty(dataList) || dataList.size()==0) return;
        commonParts(dataList,entityModel,response);
    }
    public static <T> void createTemplate(List dataList ,Class<T> entityModel , HttpServletResponse response) {
        commonParts(dataList,entityModel,response);
    }
    private static <T> void commonParts(List dataList,Class<T> entityModel , HttpServletResponse response){
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);
        try {
            EasyExcel.write(getOutputStream(response), entityModel)
                    .excelType(ExcelTypeEnum.XLSX)
                    .sheet("全部数据")
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                    .doWrite(dataList);
        } catch (Exception e) {

        }
    }

    /**
     * 导出文件时为Writer生成OutputStream
     *
     */
    private static OutputStream getOutputStream(HttpServletResponse response) throws Exception {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment");
            return response.getOutputStream();
        } catch (IOException e) {
            throw new Exception("导出excel表格失败!", e);
        }
    }
}
